package org.example.web3j.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.crypto.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.concurrent.CompletableFuture;

@Service
public class Web3jExampleService {

    @Autowired
    private Web3j web3j;

    // 创建新的以太坊钱包
//    public String createWallet(String password) throws CipherException, IOException {
//        return WalletUtils.generateNewWalletFile(password, System.getProperty("java.io.tmpdir"), false);
//    }

    // 查询账户余额
    public BigDecimal getBalance(String address) throws IOException {
        EthGetBalance response = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
        return Convert.fromWei(response.getBalance().toString(), Convert.Unit.ETHER);
    }

    // 发送 ETH 交易（同步）
    public String sendTransaction(String walletPath, String password, String toAddress, BigDecimal amount)
            throws Exception {
        Credentials credentials = WalletUtils.loadCredentials(password, walletPath);
        TransactionReceipt receipt = Transfer.sendFunds(
                web3j, credentials, toAddress, amount, Convert.Unit.ETHER
        ).send();
        return receipt.getTransactionHash();
    }

    // 发送 ETH 交易（异步）
    public CompletableFuture<String> sendTransactionAsync(String walletPath, String password,
                                                          String toAddress, BigDecimal amount) throws Exception {
        Credentials credentials = WalletUtils.loadCredentials(password, walletPath);
        return Transfer.sendFunds(
                web3j, credentials, toAddress, amount, Convert.Unit.ETHER
        ).sendAsync().thenApply(TransactionReceipt::getTransactionHash);
    }

    // 部署智能合约示例（简化版）
    public String deployContract(String walletPath, String password, String contractBytecode) throws Exception {
        Credentials credentials = WalletUtils.loadCredentials(password, walletPath);
        // 使用 Contract.deploy() 方法部署合约
        // 此处省略具体实现，需根据合约 ABI 生成 Java 包装类
        return "contractAddress";
    }
}
